package org.qydjk.console.controller.user;

import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.user.User;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.DevelopUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.ext.UserCapitalWaterEnum;
import org.qydjk.console.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/userInfo")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    /**
     * 页面跳转
     *
     * @return
     */
    @RequestMapping("/userInfo.do")
    public String userInfo() {
        return "user/userInfo/userInfo";
    }

    /**
     * 查询用户列表信息
     *
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     * @throws Exception
     */
    @RequestMapping("/dataGrid.do")
    @ResponseBody
    public Object dataGrid(Integer page, Integer rows, String sort, String order, String statusSearchWord, String typeSearchWord, String usernameSearchWord, String phoneSearchWord, String emailSearchWord) throws Exception {
        try {
            HibernatePage pager = new HibernatePage(page, rows);

            StringBuilder sb = new StringBuilder();
            sb.append("FROM User c WHERE 1 = 1 ");
            if (!StringUtil.isEmptyOrNull(statusSearchWord)) {
                sb.append(" AND c.status = " + statusSearchWord);
            }
            if (!StringUtil.isEmptyOrNull(typeSearchWord)) {
                sb.append(" AND c.type = " + typeSearchWord);
            }
            if (!StringUtil.isEmptyOrNull(usernameSearchWord)) {
                sb.append(" AND c.username LIKE '%" + usernameSearchWord + "%'");
            }
            if (!StringUtil.isEmptyOrNull(phoneSearchWord)) {
                sb.append(" AND c.phone LIKE '%" + phoneSearchWord + "%'");
            }
            if (!StringUtil.isEmptyOrNull(emailSearchWord)) {
                sb.append(" AND c.email LIKE '%" + emailSearchWord + "%'");
            }
            sb.append(" order by c." + sort + " " + order);


            StringBuilder countSb = new StringBuilder();
            countSb.append("select count(c.id) from User c WHERE 1 = 1 ");
            if (!StringUtil.isEmptyOrNull(statusSearchWord)) {
                countSb.append(" AND c.status = " + statusSearchWord);
            }
            if (!StringUtil.isEmptyOrNull(typeSearchWord)) {
                countSb.append(" AND c.type = " + typeSearchWord);
            }
            if (!StringUtil.isEmptyOrNull(usernameSearchWord)) {
                countSb.append(" AND c.username LIKE '%" + usernameSearchWord + "%'");
            }
            if (!StringUtil.isEmptyOrNull(phoneSearchWord)) {
                countSb.append(" AND c.phone LIKE '%" + phoneSearchWord + "%'");
            }
            if (!StringUtil.isEmptyOrNull(emailSearchWord)) {
                countSb.append(" AND c.email LIKE '%" + emailSearchWord + "%'");
            }
            String hql = sb.toString();
            List<User> list = baseService.findByHql(hql, pager);
            int total = baseService.getRecordCountHQL(countSb.toString());
            return new EasyUIResponse(total, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加用户页
     *
     * @return
     */
    @GetMapping("/addPage.do")
    public String addPage() {
        return "user/userInfo/userInfoAdd";
    }

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @PostMapping("/add.do")
    @ResponseBody
    public Object add(@Valid User user, String checkPwd) throws Exception {
        try {
            String pwd = user.getPwd();
            if (pwd != null && !"".equals(pwd) && pwd.equals(checkPwd)) {

                user.setRegIp(DevelopUtil.getIpAddr(request));
                String md52 = StringUtil.encodeMd5(StringUtil.encodeMd5(pwd));
                user.setPwd(md52);
//            user.setPwd();
                Date date = new Date();
                user.setRegTime(date);
                user.setMoney(new BigDecimal(0));
                user.setCreateTime(date);
                user.setUpdateTime(date);
                baseService.save(user);
                return renderSuccess("添加成功！");
            } else {
                return renderError("密码不一致");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object delete(Integer id) throws Exception {
        try {
            User user = new User();
            user.setId(id);
            baseService.delete(user);
            return renderSuccess("删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 编辑用户
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage.do")
    public String editPage(Model model, Integer id) throws Exception {
        try {
            User user = baseService.get(User.class, id);
            model.addAttribute("user", user);
            return "user/userInfo/userInfoEdit";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 编辑用户
     *
     * @param user
     * @return
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object edit(@Valid User user, String birthdayTemp) throws Exception {
        try {
            User ss = baseService.get(User.class, user.getId());
            BeanUtil.copyProperties(user, ss);

            if (!(birthdayTemp != null && !"".equals(birthdayTemp.trim()))) {
                ss.setBirthday(null);
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                ss.setBirthday(sdf.parse(birthdayTemp));
            }
            ss.setUpdateTime(new Date());
            baseService.update(ss);
            return renderSuccess("编辑成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/resetPwd.do")
    @ResponseBody
    public Object resetPwd(Integer userId) throws Exception {
        try {
            User user = baseService.get(User.class, userId);
            String md52 = StringUtil.encodeMd5(StringUtil.encodeMd5("123456"));
            user.setPwd(md52);
            baseService.update(user);
            return renderSuccess("密码已重置为: 123456");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 添加用户页
     *
     * @return
     */

    @RequestMapping("/rechargePage.do")
    public String rechargePage(Model model, Integer id) throws Exception {
        try {
            User user = baseService.get(User.class, id);
            model.addAttribute("user", user);
            return "user/userInfo/recharge";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加用户
     *
     * @param
     * @return
     */
    @PostMapping("/recharge.do")
    @ResponseBody
    public Object recharge(Integer id, String flag, String money) throws Exception {
        try {

            User user = baseService.get(User.class, id);

            UserCapitalWaterEnum userCapitalWaterEnum = null;
            if ("0".equals(flag)) {
                userCapitalWaterEnum = UserCapitalWaterEnum.RECHARGE;
            } else if ("1".equals(flag)) {
                userCapitalWaterEnum = UserCapitalWaterEnum.REDUCE;
            }

            userService.addOrSubtractMoney(user, userCapitalWaterEnum, money);


            return renderSuccess("成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
